package com.epalmpay.service.weixin.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.tools.Tool;

import com.epalmpay.dto.member.MemberWxInfoDTO;
import com.epalmpay.entity.*;
import com.epalmpay.entity.Response;
import com.epalmpay.entity.profit.Profit;
import com.epalmpay.entity.profit.ProfitMemberMonth;
import com.epalmpay.mapper.*;
import com.epalmpay.mapper.profit.ProfitMemberMonthMapper;
import com.epalmpay.service.bonus.IBonusService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.util.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.config.Global;
import com.epalmpay.dto.activity.CouponHelp;
import com.epalmpay.dto.activity.RedpackageUserDTO;
import com.epalmpay.dto.member.MemberInDTO;
import com.epalmpay.dto.member.MemberOutDTO;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.payplat.FindbackPayPwd;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayReqQRCode;
import com.epalmpay.payplat.PayUpdateData;
import com.epalmpay.payplat.PayUpdatePayPwd;
import com.epalmpay.payplat.PayUserAccounts;
import com.epalmpay.payplat.UnPayConsumption;
import com.epalmpay.payplat.result.PayCrcodeCallback;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.activity.ICouponUserService;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWxApiService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.util.AES;
import com.epalmpay.util.AmountUtils;
import com.epalmpay.util.Const;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.FileUploadContorller;
import com.epalmpay.util.StringUtil;
import com.epalmpay.util.Tools;
import com.epalmpay.util.code.CodeUtil;
import com.epalmpay.util.code.QRCodeParams;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.Rsa;
import com.epalmpay.util.payplat.UtilFun;

import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;


@Service("wxApiService")
public class WxApiServiceImpl implements IWxApiService {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Resource
    private MemberCardMapper memberCardMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private CouponUserMapper couponUserMapper;
    @Resource
    private MemberSignMapper memberSignMapper;
    @Resource
    private RedpackageUserMapper redpackageUserMapper;
    @Resource
    private RedpackageMapper redpackageMapper;
    @Resource
    private ActivityUnroutineMapper activityUnroutineMapper;
    @Resource
    private OrderServiceGoodMapper orderServiceGoodMapper;
    @Resource
    private BonusVerifyLogMapper bonusVerifyLogMapper;
    @Resource
    private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;
    @Resource
    private MallCategoryMapper mallCategoryMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private UserbaseMapper userBaseMapper;
    @Resource
    private IMemberService memberService;

    @Resource
    private StatisMemberMapper statisMemberMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private TradeOfflineMapper tradeOfflineMapper;

    @Resource
    private ICouponUserService couponUserService;
    @Resource
    private CrcodeMapper crcodeMapper;
    @Resource
    protected WxService wxService;

    @Resource
    protected IWxBaseService wxBaseService;
    @Resource
    private IRedPackageUserService redPackageUserService;

    @Resource
    private MemberGradeMapper memberGradeMapper;
    @Resource
    private ActivityRoutinesignedMapper activityRoutinesignedMapper;
    @Resource
    private IBonusService bonusService;
    @Resource
    private ActivityBaseMapper activityBaseMapper;

    @Resource
    private StatisMemberMonthMapper statisMemberMonthMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private ActivityRoutineRegisterMapper activityRoutineRegisterMapper;
    @Resource
    private MallGoodCommentMapper mallGoodCommentMapper;
    @Autowired
    @Lazy
    private ITemplateMailSendService templateMailSendService;
    @Resource
    private ProfitMemberMonthMapper profitMemberMonthMapper;
    @Resource
    private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
    @Resource
    private StatisMemberDayMapper statisMemberDayMapper;
    @Resource
    private GroupWxconfigMapper groupWxconfigMapper;

    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;

    @Resource
    private ProfitMapper profitMapper;


    @Override
    public Map<String, Object> findCategory(String groupId, String level, Integer goodBigtype) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();


        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(level)) {
            throw new ApplicationException(Rescode.FAIL, "level 不能为空！");
        }

        List<MallCategory> mallCategorys = mallCategoryMapper.selectGroupId(Long.parseLong(groupId), goodBigtype);
        List<Map<String, Object>> mallCategoryList = new ArrayList<Map<String, Object>>();

        for (MallCategory mallCategory : mallCategorys) {
            Map<String, Object> mallCategoryDetail = new HashMap<String, Object>();
            mallCategoryDetail.put("category_id", mallCategory.getId());
            mallCategoryDetail.put("category_icon", mallCategory.getIcon());
            mallCategoryDetail.put("category_name", mallCategory.getName());
            mallCategoryList.add(mallCategoryDetail);
            if (Long.parseLong(level) == 2) {
                //获取2级类目的list
                Long parentId = mallCategory.getId();
                mallCategorys = mallCategoryMapper.querySubCategoryList(parentId, goodBigtype);
                List<Map<String, Object>> subcategoryList = new ArrayList<Map<String, Object>>();
                for (MallCategory mallCategory2 : mallCategorys) {
                    Map<String, Object> subMallCategoryDetail = new HashMap<String, Object>();
                    subMallCategoryDetail.put("category_id", mallCategory2.getId());
                    subMallCategoryDetail.put("category_icon", mallCategory2.getIcon());
                    subMallCategoryDetail.put("category_name", mallCategory2.getName());
                    subcategoryList.add(subMallCategoryDetail);
                }
                if (subcategoryList.size() > 0) {
                    mallCategoryDetail.put("subcategory_list", subcategoryList);
                }
                if (subcategoryList.size() == 0) {
                    mallCategoryDetail.put("subcategory_list", subcategoryList);
                }

            }
        }
        if (mallCategoryList.size() > 0) {
            map.put("category_list", mallCategoryList);
        }


        return map;

    }


    //查询优惠券列表
    public Map<String, Object> getCouponCanGetList(String groupId, String openId, String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        List<Coupon> coupons = couponMapper.selectCanGetCouponList(Long.parseLong(groupId));
        List<Map<String, Object>> couponList = new ArrayList<Map<String, Object>>();
        for (Coupon coupon : coupons) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("coupon_id", coupon.getId());
            detail.put("coupon_type", ActivityEnum.CouponType.fromType(coupon.getCouponType()).getName());
            detail.put("coupon_name", coupon.getName());
            detail.put("coupon_money", CouponHelp.getFaceValueStr(coupon.getCouponType(), coupon.getValue()));
            detail.put("coupon_qualification", AmountUtils.changeF2Y(coupon.getLimitAmount() == null ? 0 : coupon.getLimitAmount().longValue()));
            detail.put("coupon_valid_time", CouponHelp.getValidTimeStr(coupon.getValidTimeType(), coupon.getValidStartTime(),
                    coupon.getValidEndTime(), coupon.getDays()));
            detail.put("coupon_use_store", CouponHelp.getShopStr(coupon.getShopids()));
            detail.put("exchange_place", coupon.getExchangePlace());
            couponList.add(detail);
        }
        if (couponList.size() > 0) {
            map.put("coupon_list", couponList);
        }
        return map;
    }

    //查询会员签到列表
    @Override
    public Map<String, Object> memberSignList(String groupId, String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        Date time = new Date();

        Member member = memberMapper.findMemberPictureById(Long.parseLong(memberId));
        map.put("picture", member.getPicture());
        map.put("memberName", member.getName());
//		List<MemberSign> memberSigns = memberSignMapper.queryMemberSignList(Long.parseLong(memberId),time);
        MemberSign memberSigns = memberSignMapper.queryMemberSign(Long.parseLong(memberId), time);

        Integer totalCount = memberSignMapper.queryqueryMemberSignCount(Long.parseLong(groupId), Long.parseLong(memberId));
        Integer monthCount = memberSignMapper.queryMonthMemberSignCount(Long.parseLong(groupId), time, Long.parseLong(memberId));

        if (totalCount != 0) {
            map.put("totalCount", totalCount);
        } else {
            map.put("totalCount", 0);
        }
        if (monthCount != 0) {
            map.put("monthCount", monthCount);
        } else {
            map.put("monthCount", 0);
        }
        if (memberSigns != null) {
            String[] days = memberSigns.getDays().split(",");
            map.put("days", days);
//			map.put("picture",memberSigns.getPicture());
//			map.put("memberName",memberSigns.getMemberName());
        } else {
            String[] days = new String[]{};
            map.put("days", days);
        }

        //取得签到配置信息
        //取得签到活动
        ActivityRoutinesigned rule = activityRoutinesignedMapper.selectSignActivityByGroupId(Long.parseLong(groupId));
        Integer signSendType = 0;
        Integer sigleTimeReward = 0;
        Integer constantTimes = 0;
        Integer constantReward = 0;
        Integer secondSendType = 0;
        Time singedStartTime = null;
        Time singedEndTime = null;
        String secondCouponName = "";
        String secondRedpackageName = "";
        Integer thirdSendType = 0;
        String thirdCouponName = "";
        String thirdRedpackageName = "";

        if (rule != null) {
            signSendType = rule.getSignSendType();
            sigleTimeReward = rule.getSigleTimeReward();
            constantTimes = rule.getConstantTimes();
            constantReward = rule.getConstantReward();
            secondSendType = rule.getSecondSendType();
            secondCouponName = rule.getSecondCouponName();
            secondRedpackageName = rule.getSecondRedpackageName();
            thirdSendType = rule.getThirdSendType();
            thirdCouponName = rule.getThirdCouponName();
            thirdRedpackageName = rule.getThirdRedpackageName();
            singedStartTime = rule.getSingedStartTime();
            singedEndTime = rule.getSingedEndTime();
        }
        map.put("signSendType", signSendType);
        map.put("singedStartTime", singedStartTime);
        map.put("singedEndTime", singedEndTime);
        map.put("sigleTimeReward", sigleTimeReward);
        map.put("constantTimes", constantTimes);
        map.put("constantReward", constantReward);
        map.put("secondSendType", secondSendType);
        map.put("secondCouponName", secondCouponName);
        map.put("secondRedpackageName", secondRedpackageName);
        map.put("thirdSendType", thirdSendType);
        map.put("thirdCouponName", thirdCouponName);
        map.put("thirdRedpackageName", thirdRedpackageName);

        return map;
    }


    /***
     * 会员签到
     * @param memberId
     * @return 不设签到积分规则时，不返回参数
     * signSendType:签到奖励类型(1:返现;4:积分)
     * sigleTimeReward:单次签到奖励
     * constantReward:连续签到奖励
     * secondCouponId:第二次连续签到奖励优惠券id
     * secondCouponName:第二次连续签到奖励优惠券名称
     * secondRedpackageId:第二次连续签到奖励红包id
     * secondRedpackageName:第二次连续签到奖励红包名称
     * thirdCouponId:第三次连续签到奖励优惠券id
     * thirdCouponName:第三次连续签到奖励优惠券名称
     * thirdRedpackageId:第三次连续签到奖励红包id
     * thirdRedpackageName:第三次连续签到奖励红包名称
     * memo:备注
     * @throws Exception
     */
    public Map<String, Object> insertMemberSign(Long memberId) throws Exception {
        int result = 0;
        if (memberId == null) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }

        //取得会员积分
        Member member = memberMapper.queryBonusAmount(memberId);
        if (member == null)
            throw new ApplicationException("会员id:" + memberId + "不存在!");

        Date date = new Date();
        MemberSign memberSign = new MemberSign();
        memberSign.setMemberId(memberId);
        memberSign.setGroupId(member.getGroupId());
        memberSign.setGmtCreate(date);

        MemberSign mem = memberSignMapper.queryData(memberSign);
        if (mem.getTotalCount() > 0) {
            throw new ApplicationException(Rescode.FAIL, "今日已签到,不能重复签到");
        }
        //插入签到记录
        memberSign.setGmtModified(date);
        result = memberSignMapper.insert(memberSign);

        Map<String, Object> map = new HashMap<String, Object>();
        Integer signSendType = 0;
        Integer sigleTimeReward = 0;
        Integer constantReward = 0;
        Long secondCouponId = 0L;
        String secondCouponName = "";
        Long secondRedpackageId = 0L;
        String secondRedpackageName = "";
        Long thirdCouponId = 0L;
        String thirdCouponName = "";
        Long thirdRedpackageId = 0L;
        String thirdRedpackageName = "";
        String memo = "";
        BonusSendLog bonusSendLog = null;
        ActivityBase activityBase = null;

        //取得签到活动
        ActivityRoutinesigned activityRoutinesigned = activityRoutinesignedMapper.selectSignActivityByGroupId(member.getGroupId());
        activityRoutinesigned.setUsedAmount(activityRoutinesigned.getUsedAmount() == null ? 0 : activityRoutinesigned.getUsedAmount());

        if (activityRoutinesigned == null) {
            return map;
        }
        if (activityRoutinesigned.getSignedTimeType() == ActivityEnum.TimeRangeType.TimeRange.getType()) {
            Time nowTime = Time.valueOf(DateUtil.fomatDate(new Date(), DateUtil.sdfTimeHMS));
            if (nowTime.compareTo(activityRoutinesigned.getSingedStartTime()) < 0 || nowTime.compareTo(activityRoutinesigned.getSingedEndTime()) > 0)
                throw new ApplicationException(Rescode.FAIL, "不在签到时间范围内,不能签到");
        }
        //
        if (activityRoutinesigned.getSignSendType() == ActivityEnum.ActivitySendType.Bonus.getType()) {
            signSendType = ActivityEnum.ActivitySendType.Bonus.getType();

            MemberSign signList = memberSignMapper.queryMemberSign(memberId, date);
            //计算签到积分奖励
            int count = Tools.getLastContinusSignTimes(signList.getDays());
            if (count < activityRoutinesigned.getConstantTimes()) {//单次签到
                if (activityRoutinesigned.getSigleTimeReward() > (activityRoutinesigned.getMaxAmount() - activityRoutinesigned.getUsedAmount())) {
                    memo = "积分预算已用完";
                } else {
                    sigleTimeReward = activityRoutinesigned.getSigleTimeReward();
                    //积分发放
                    bonusSendLog = BonusSendLog.build(member.getGroupId(), memberId,
                            ActivityEnum.BonusSendType.Sign.getType(), sigleTimeReward, ActivityEnum.BonusSendStatus.Accounted.getType(),
                            null, null, null, "单次签到奖励", activityRoutinesigned.getBaseId());
                    bonusService.sendOneMemberBonus(bonusSendLog);
                    //更新已使用积分
                    activityBase = new ActivityBase();
                    activityBase.setId(activityRoutinesigned.getBaseId());
                    activityBase.setGmtModified(date);
                    activityBase.setUsedAmount(activityRoutinesigned.getUsedAmount() + sigleTimeReward);
                    activityBaseMapper.updateByPrimaryKeySelective(activityBase);
                }
            } else {//连续签到
                if (activityRoutinesigned.getConstantReward() > (activityRoutinesigned.getMaxAmount() - activityRoutinesigned.getUsedAmount())) {
                    //throw new ApplicationException(Rescode.FAIL, "积分预算已用完不在签到时间范围内,不能签到");
                    memo = "积分预算已用完";
                } else {
                    constantReward = activityRoutinesigned.getConstantReward();
                    //积分发放
                    bonusSendLog = BonusSendLog.build(member.getGroupId(), memberId,
                            ActivityEnum.BonusSendType.Sign.getType(), constantReward, ActivityEnum.BonusSendStatus.Accounted.getType(),
                            null, null, null, "连续签到奖励", activityRoutinesigned.getBaseId());
                    bonusService.sendOneMemberBonus(bonusSendLog);
                    //更新已使用积分
                    activityBase = new ActivityBase();
                    activityBase.setId(activityRoutinesigned.getBaseId());
                    activityBase.setGmtModified(date);
                    activityBase.setUsedAmount(activityRoutinesigned.getUsedAmount() + constantReward);
                    activityBaseMapper.updateByPrimaryKeySelective(activityBase);
                }
            }

            //如果预算使用完毕则结束活动
            if (activityRoutinesigned.getUsedAmount() + constantReward >= activityRoutinesigned.getMaxAmount()) {
                if (activityRoutinesigned.getMaxAmount() != 0) {
                    activityBase = new ActivityBase();
                    activityBase.setId(activityRoutinesigned.getBaseId());
                    activityBase.setGmtModified(date);
                    activityBase.setStatus(ActivityEnum.ActivityStatus.Over.getType());
                    activityBaseMapper.updateByPrimaryKeySelective(activityBase);
                }

            }

            //叠加连续赠送
            int timeth = Tools.getContinusSignTimeth(signList.getDays(), activityRoutinesigned.getConstantTimes());
            switch (timeth) {
                case 2:
                    if (activityRoutinesigned.getSecondSendType() == ActivityEnum.ActivitySendType.RedPackage.getType()) {
                        try {
                            result = redPackageUserService.sendOneMemberRedPackage(memberId, activityRoutinesigned.getSecondRedpackageId(),
                                    activityRoutinesigned.getBaseId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "连续2次签到", null);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
                            secondRedpackageId = activityRoutinesigned.getSecondRedpackageId();
                            secondRedpackageName = activityRoutinesigned.getSecondRedpackageName();
                            //map.put("secondRedpackageId",activityRoutinesigned.getSecondRedpackageId());
                            //map.put("secondRedpackageName",activityRoutinesigned.getSecondRedpackageName());
                        }
                    } else if (activityRoutinesigned.getSecondSendType() == ActivityEnum.ActivitySendType.Coupon.getType()) {
                        try {
                            result = couponUserService.sendOneMemberCoupon(memberId, activityRoutinesigned.getSecondCouponId(),
                                    activityRoutinesigned.getBaseId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "连续2次签到", null);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
                            secondCouponId = activityRoutinesigned.getSecondCouponId();
                            secondCouponName = activityRoutinesigned.getSecondCouponName();
                            //map.put("secondCouponId", activityRoutinesigned.getSecondCouponId());
                            //map.put("secondCouponName", activityRoutinesigned.getSecondCouponName());
                        }
                    } else if (activityRoutinesigned.getSecondSendType() == ActivityEnum.ActivitySendType.Bonus.getType()) {
                        try {
                            BonusSendLog bonusSendLog_2 = BonusSendLog.build(activityBase.getGroupId(), memberId, ActivityEnum.BonusSendType.routineActivitySign.getType(),
                                    Integer.parseInt(String.valueOf(activityRoutinesigned.getSecondIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(), null, null, null, "连续2次签到", activityBase.getId());
                            result = bonusService.sendOneMemberBonus(bonusSendLog_2);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
//							secondCouponId = activityRoutinesigned.getSecondCouponId();
//							secondCouponName = activityRoutinesigned.getSecondCouponName();
                            //map.put("secondCouponId", activityRoutinesigned.getSecondCouponId());
                            //map.put("secondCouponName", activityRoutinesigned.getSecondCouponName());
                        }
                    }
                    break;
                case 3:
                    if (activityRoutinesigned.getThirdSendType() == ActivityEnum.ActivitySendType.RedPackage.getType()) {
                        try {
                            result = redPackageUserService.sendOneMemberRedPackage(memberId, activityRoutinesigned.getThirdRedpackageId(),
                                    activityRoutinesigned.getBaseId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "连续3次签到", null);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
                            thirdRedpackageId = activityRoutinesigned.getThirdRedpackageId();
                            thirdRedpackageName = activityRoutinesigned.getThirdRedpackageName();
                        }
                    } else if (activityRoutinesigned.getThirdSendType() == ActivityEnum.ActivitySendType.Coupon.getType()) {
                        try {
                            result = couponUserService.sendOneMemberCoupon(memberId, activityRoutinesigned.getThirdCouponId(),
                                    activityRoutinesigned.getBaseId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), "连续3次签到", null);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
                            thirdCouponId = activityRoutinesigned.getThirdCouponId();
                            thirdCouponName = activityRoutinesigned.getThirdCouponName();
                        }
                    } else if (activityRoutinesigned.getThirdSendType() == ActivityEnum.ActivitySendType.Bonus.getType()) {
                        try {
                            BonusSendLog bonusSendLog_3 = BonusSendLog.build(activityBase.getGroupId(), memberId, ActivityEnum.BonusSendType.routineActivitySign.getType(),
                                    Integer.parseInt(String.valueOf(activityRoutinesigned.getThirdIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(), null, null, null, "连续3次签到", activityBase.getId());
                            result = bonusService.sendOneMemberBonus(bonusSendLog_3);
                        } catch (Exception ae) {
                            logger.error(ae);
                            result = 0;
                        }
                        if (result == 1) {
//							thirdCouponId = activityRoutinesigned.getThirdCouponId();
//							thirdCouponName = activityRoutinesigned.getThirdCouponName();
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        if (activityRoutinesigned.getUsedAmount() + sigleTimeReward >= activityRoutinesigned.getMaxAmount()) {

        }

        map.put("signSendType", signSendType);
        map.put("sigleTimeReward", sigleTimeReward);
        map.put("constantReward", constantReward);
        map.put("secondCouponId", secondCouponId);
        map.put("secondCouponName", secondCouponName);
        map.put("secondRedpackageId", secondRedpackageId);
        map.put("secondRedpackageName", secondRedpackageName);
        map.put("thirdCouponId", thirdCouponId);
        map.put("thirdCouponName", thirdCouponName);
        map.put("thirdRedpackageId", thirdRedpackageId);
        map.put("thirdRedpackageName", thirdRedpackageName);
        map.put("memo", memo);
        return map;
    }

    @Override
    public Integer querytodaymemberSign(Long memberId, Long groupId) throws Exception {
        Integer signState = 0;
        //查询是否有签到权限
        int activity = activityRoutinesignedMapper.selectSignCountByGroupId(groupId);
        if (activity > 0) {
            MemberSign record = new MemberSign();
            record.setMemberId(memberId);
            record.setGmtCreate(new Date());
            MemberSign memberSign = memberSignMapper.querytodaymemberSign(record);
            if (memberSign != null) {
                signState = 1;
            }
        } else {
            signState = 2;
        }
        return signState;
    }

    @Override
    public Map<String, Object> getRedpackList(String groupId, String openId, String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        //Integer status = ActivityEnum.RedpackageGetStatus.Gotten.getType();
        List<RedpackageUser> redpackageUsers = redpackageUserMapper.queryRedPackUserList(Long.parseLong(groupId), Long.parseLong(memberId), null);
        List<Map<String, Object>> redpackageUserList = new ArrayList<Map<String, Object>>();
        for (RedpackageUser redpackageUser : redpackageUsers) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("redpackageuser_id", redpackageUser.getId());
            detail.put("redpackage_name", redpackageUser.getRedpackageName());
            if (redpackageUser.getRedpackageType() == 1) {
                detail.put("face_value", redpackageUser.getFaceValue());
            } else {
                detail.put("face_value", redpackageUser.getRealAmount());
            }
            detail.put("status", redpackageUser.getGetStatus());
            detail.put("valid_end_time", DateUtil.fomatDate(redpackageUser.getValidTime(), DateUtil.sdfTime));
            //detail.put("get_time",redpackageUser.getGetTime());
            detail.put("get_time", DateUtil.fomatDate(redpackageUser.getGetTime(), DateUtil.sdfTime));

            redpackageUserList.add(detail);
        }
        if (redpackageUserList.size() > 0) {
            map.put("redpackageUser_List", redpackageUserList);
        }
        return map;
    }

    @Override
    public Map<String, Object> getRedpackCanGetList(String groupId, String openId, String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        //可领取 待修改
        Integer status = ActivityEnum.RedpackageGetStatus.Received.getType();//枚举代表可领取
        List<RedpackageUserDTO> redpackageUserDTOS = redpackageUserMapper.selectCanGetRedpackageList(Long.parseLong(memberId), status);
        //List<Redpackage> redpackages = redpackageMapper.queryRedPackList(Long.parseLong(groupId),status);
        List<Map<String, Object>> redpackageList = new ArrayList<Map<String, Object>>();
        for (RedpackageUserDTO redpackageUserDTO : redpackageUserDTOS) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("redpackageuser_id", redpackageUserDTO.getId());
            detail.put("redpackage_name", redpackageUserDTO.getRedpackageName());
            detail.put("redpackage_type", redpackageUserDTO.getRedpackageType());
            detail.put("get_status", redpackageUserDTO.getGetStatus());
            detail.put("redpachage_id", redpackageUserDTO.getRedpackageId());
            if (redpackageUserDTO.getRedpackageType() == 1) {
                detail.put("face_value", redpackageUserDTO.getFaceValue());
            } else {
                detail.put("max_value", redpackageUserDTO.getMax_Value());
                detail.put("min_value", redpackageUserDTO.getMinValue());
                detail.put("face_value", redpackageUserDTO.getRealAmount());
            }
            String date = DateUtil.fomatDate(redpackageUserDTO.getValidEndTime(), DateUtil.sdfDayC);
            detail.put("valid_end_time", date);
            if (redpackageUserDTO.getGetTime() != null) {
                detail.put("get_time", DateUtil.fomatDate(redpackageUserDTO.getGetTime(), DateUtil.sdfTimeC));
            } else {
                detail.put("get_time", "");
            }

            redpackageList.add(detail);
        }
        if (redpackageList.size() > 0) {
            map.put("redpackageUser_List", redpackageList);
        }
        return map;
    }

    @Override
    public Map<String, Object> couponCanGetDetail(String memberId, String couponId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }
        if (Tools.isEmpty(couponId)) {
            throw new ApplicationException(Rescode.FAIL, "couponId不能为空！");
        }
        Coupon coupon = couponMapper.selectByPrimaryKey(Long.parseLong(couponId));
        if (coupon != null) {
            map.put("coupon_id", coupon.getId());
            map.put("coupon_icon", "");
            map.put("coupon_type", ActivityEnum.CouponType.fromType(coupon.getCouponType()).getName());
            map.put("coupon_name", coupon.getName());
            map.put("coupon_money", CouponHelp.getFaceValueStr(coupon.getCouponType(), coupon.getValue()));
//			map.put("coupon_money",coupon.getValue()/100);
            map.put("coupon_qualification", AmountUtils.changeF2Y(coupon.getLimitAmount() == null ? 0 : coupon.getLimitAmount().longValue()));
            map.put("coupon_valid_time", CouponHelp.getValidTimeStr(coupon.getValidTimeType(), coupon.getValidStartTime(),
                    coupon.getValidEndTime(), coupon.getDays()));
            map.put("coupon_peruser", coupon.getAmountPeruser());
            map.put("verify_readd_count", coupon.getVerifyReaddCount());
            map.put("coupon_use_store", CouponHelp.getShopStr(coupon.getShopids()));
            //exchange_place 为1 商品类型good_type 写死了3  exchange_place为2 的时候 good_type 1:表示服务商品 2 商城商品
            if (coupon.getExchangePlace() == 1) {
                map.put("good_type", 3);
            } else {
                map.put("good_type", coupon.getGoodType());
            }


        }
        return map;
    }

    @Override
    public int insertCouponUser(String memberId, String couponId) throws Exception {
        int result = 0;
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (Tools.isEmpty(couponId)) {
            throw new ApplicationException(Rescode.FAIL, "couponId 不能为空！");
        }

        result = couponUserService.sendOneMemberCoupon(Long.parseLong(memberId), Long.parseLong(couponId),
                null, ActivityEnum.RedPackageGetType.GetPage.getType(), null);
        return result;

    }

    @Override
    public Map<String, Object> getActivityList(String groupId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (Tools.isEmpty(groupId)) {
            throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
        }
        List<ActivityUnroutine> activityUnroutines = activityUnroutineMapper.queryActivityList(Long.parseLong(groupId));
        List<Map<String, Object>> activityUnroutineList = new ArrayList<Map<String, Object>>();
        for (ActivityUnroutine activityUnroutine : activityUnroutines) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("activity_icon", activityUnroutine.getIconUrl());
            detail.put("activity_page_icon", activityUnroutine.getMainPageUrl());
            detail.put("activity_id", activityUnroutine.getActivityId());
            detail.put("activity_name", activityUnroutine.getActivityName());
            detail.put("activity_type", ActivityEnum.ActivityType.fromType(activityUnroutine.getActivityType()).getName());
            detail.put("activity_use_store", CouponHelp.getShopStr(activityUnroutine.getShopids()));
            activityUnroutineList.add(detail);
        }
        if (activityUnroutineList.size() > 0) {
            map.put("activityUnroutine_list", activityUnroutineList);
        }
        return map;
    }

    @Override
    public Map<String, Object> activityDetail(String activityId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(activityId)) {
            throw new ApplicationException(Rescode.FAIL, "activityId不能为空！");
        }
        ActivityUnroutine activityUnroutine = activityUnroutineMapper.queryActivityDetailById(Long.parseLong(activityId));

        if (activityUnroutine != null) {

            map.put("activity_icon", activityUnroutine.getMainPageUrl());
//			map.put("activity_icon",activityUnroutine.getIconUrl());
            map.put("activity_name", activityUnroutine.getActivityName());
            map.put("activity_description", activityUnroutine.getContent());
            map.put("activity_time", activityUnroutine.getValidTimeStr());
            map.put("activity_type", activityUnroutine.getActivityType());

            List<ActivityUnroutineRule> activityUnroutineRules = activityUnroutineRuleMapper.queryActivityUnroutineRuleByActivityId(Long.parseLong(activityId));
            List<Map<String, Object>> activityRuleList = new ArrayList<Map<String, Object>>();
            for (ActivityUnroutineRule activityUnroutineRule : activityUnroutineRules) {
                Map<String, Object> activityRuleMap = new HashMap<String, Object>();
                activityRuleMap.put("mini_amount", activityUnroutineRule.getMiniAmount());
                activityRuleMap.put("back_mode", activityUnroutineRule.getBackMoneyMode());
                activityRuleMap.put("face_value", activityUnroutineRule.getFaceValue());
                activityRuleMap.put("act_name", activityUnroutineRule.getRedpackageOrCouponName());
                map.put("send_type", activityUnroutineRule.getSendType());

                activityRuleList.add(activityRuleMap);
            }

            if (activityRuleList.size() > 0) {
                map.put("activityRule_list", activityRuleList);
            }
            return map;

        }

        return map;
    }

    @Override
    public Map<String, Object> queryCouponHaveGottenList(String memberId, Integer amount) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }

        Integer couponUseStatus = ActivityEnum.CouponUseStatus.Received.getType();
        List<CouponUser> couponUsers = couponUserMapper.queryCouponHaveGottenList(Tools.isEmpty(memberId) ? null : Long.parseLong(memberId), couponUseStatus);
        List<Map<String, Object>> couponUserList = new ArrayList<Map<String, Object>>();
        for (CouponUser couponUser : couponUsers) {
            Integer limitAmount = couponUser.getLimitAmount() == null ? 0 : couponUser.getLimitAmount();
            if (amount != null && limitAmount > amount)
                continue;

            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("couponuser_id", couponUser.getId());
            detail.put("coupon_id", couponUser.getCouponId());
            detail.put("coupon_name", couponUser.getCouponName());
            detail.put("coupon_code", couponUser.getCouponCode());
            detail.put("shop_name", couponUser.getShopName());
            detail.put("valid_start_date", DateUtil.fomatDate(couponUser.getValidStartTime(), DateUtil.sdfDay));
            detail.put("valid_end_date", DateUtil.fomatDate(couponUser.getValidTime(), DateUtil.sdfDay));
            detail.put("coupon_type", ActivityEnum.CouponType.fromType(couponUser.getCouponType()).getName());
            detail.put("purpose_type", couponUser.getPurposeType());
            detail.put("face_value", AmountUtils.changeF2Y(couponUser.getLimitAmount() == null ? 0 : couponUser.getFaceValue().longValue()));
            detail.put("coupon_qualification", AmountUtils.changeF2Y(limitAmount.longValue()));
            detail.put("activity_use_store", CouponHelp.getShopStr(couponUser.getShopids()));
            detail.put("exchange_place", couponUser.getExchangePlace());

            couponUserList.add(detail);
        }
        if (couponUserList.size() > 0) {
            map.put("couponUser_list", couponUserList);
        }
        return map;
    }

    @Override
    public Map<String, Object> queryCouponhaveusedlist(String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        Integer couponUseStatus = ActivityEnum.CouponUseStatus.Verified.getType();
        List<CouponUser> couponUsers = couponUserMapper.queryCouponhaveusedlist(Long.parseLong(memberId), couponUseStatus);
        List<Map<String, Object>> couponUserList = new ArrayList<Map<String, Object>>();
        for (CouponUser couponUser : couponUsers) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("coupon_id", couponUser.getCouponId());
            detail.put("coupon_name", couponUser.getCouponName());
            if(couponUser.getShopName() !=null){
                detail.put("shop_name", couponUser.getShopName());
            }else{
                detail.put("shop_name","");
            }
            detail.put("coupon_use_status", couponUser.getCouponUseStatus());
            if(couponUser.getVerifyTime() !=null){
                detail.put("verify_time", DateUtil.fomatDate(couponUser.getVerifyTime(), DateUtil.sdfTime));
            }else{
                detail.put("verify_time", "");
            }
            detail.put("coupon_type", ActivityEnum.CouponType.fromType(couponUser.getCouponType()).getName());
            detail.put("coupon_qualification", AmountUtils.changeF2Y(couponUser.getLimitAmount() == null ? 0 : couponUser.getLimitAmount().longValue()));
            detail.put("activity_use_store", CouponHelp.getShopStr(couponUser.getShopids()));
            detail.put("face_value", AmountUtils.changeF2Y(couponUser.getLimitAmount() == null ? 0 : couponUser.getFaceValue().longValue()));
            couponUserList.add(detail);
        }
        if (couponUserList.size() > 0) {
            map.put("couponUser_list", couponUserList);
        }
        return map;
    }

    @Override
    public Map<String, Object> queryShopGoodOrderList(String openId, String memberId, String orderStatus, Integer pageNo,
                                                      Integer pageSize) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("memberId", memberId);
        if (orderStatus != "" && orderStatus != null) {
            map.put("orderStatus", orderStatus);
        }


        int sumCount = orderServiceGoodMapper.queryShopGoodOrderCount(map);

        if (sumCount <= 0)
            return null;

        map.put("limit", pageSize);
        map.put("start", pageSize * (pageNo - 1));


        List<OrderServiceGood> orderServiceGoods = orderServiceGoodMapper.queryShopGoodOrderList(map);
        List<Map<String, Object>> orderServiceGoodList = new ArrayList<Map<String, Object>>();
        for (OrderServiceGood orderServiceGood : orderServiceGoods) {
            Map<String, Object> detail = new HashMap<String, Object>();
            detail.put("order_no", orderServiceGood.getOrderNo());
            detail.put("gmt_create", DateUtil.fomatDate(orderServiceGood.getGmtCreate(), DateUtil.sdfTime));
            detail.put("order_status", orderServiceGood.getOrderStatus());
//			detail.put("shop_name", orderServiceGood.getShopName());
            detail.put("good_id", orderServiceGood.getGoodId());
            detail.put("good_name", orderServiceGood.getGoodName());
            detail.put("original_price", orderServiceGood.getSalePrice());
            detail.put("buy_number", orderServiceGood.getNumber());
            detail.put("order_amount", orderServiceGood.getOrderAmount());
//			detail.put("order_amount", orderServiceGood.getRealAmount());
//			detail.put("sum_price", orderServiceGood.getNumber()*orderServiceGood.getPromotionPrice());
            Integer sum_price = orderServiceGood.getOrderAmount() - orderServiceGood.getDiscountAmount();
            detail.put("sum_price", sum_price > 0 ? sum_price : 0);

            if(orderServiceGood.getVaildDate() == null) {
                detail.put("valid_date", "无期限");
            } else {
                String date = DateUtil.fomatDate(orderServiceGood.getVaildDate(), DateUtil.sdfDays);
                date = date.substring(0, 4) + '年' + date.substring(4, 6) + '月' + date.substring(6, date.length()) + '日';
                detail.put("valid_date", date);
            }
            detail.put("icon_picture", orderServiceGood.getIconPicture());
            detail.put("promotion_price", orderServiceGood.getPromotionPrice());
            orderServiceGoodList.add(detail);
        }
        if (orderServiceGoodList.size() > 0) {
            map.put("orderServiceGood_list", orderServiceGoodList);
        } else {
            throw new ApplicationException("未找到记录");
        }
        return map;

    }

    @Override
    public Map<String, Object> queryOrderDetail(String memberId, String orderId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();


        if (Tools.isEmpty(orderId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }

        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderId);
        if (tradeOffline == null) {
            throw new ApplicationException(Rescode.FAIL, "订单信息不存在！");
        }


        OrderServiceGood orderServiceGood = orderServiceGoodMapper.queryOrderById(orderId, Long.parseLong(memberId));
        if (orderServiceGood != null) {
            //map.put("shop_name", orderServiceGood.getShopName());
            map.put("good_name", orderServiceGood.getGoodName());
            map.put("good_icon", orderServiceGood.getIconPicture());
            map.put("sale_price", orderServiceGood.getSalePrice());
            map.put("promotion_price", orderServiceGood.getPromotionPrice());
            map.put("buy_number", orderServiceGood.getNumber());
            map.put("order_amount", orderServiceGood.getOrderAmount());
            map.put("discount_amount", orderServiceGood.getDiscountAmount());
            map.put("real_amount", orderServiceGood.getRealAmount());
            map.put("order_id", orderServiceGood.getId());
            map.put("order_status", orderServiceGood.getOrderStatus());
            map.put("gmt_create", orderServiceGood.getGmtCreate());
            map.put("used_count", orderServiceGood.getUsedNumber());
            map.put("valid_date", orderServiceGood.getVaildDate());

            //取得订单明细详情列表
            List<OrderServiceGoodDetail> orderServiceGoodDetails = orderServiceGoodDetailMapper.queryOrderServiceDetailById(orderId, Long.parseLong(memberId));
            List<Map<String, Object>> orderServiceGoodDetailList = new ArrayList<Map<String, Object>>();
            for (OrderServiceGoodDetail orderServiceGoodDetail : orderServiceGoodDetails) {
                Map<String, Object> orderDetail = new HashMap<String, Object>();
                orderDetail.put("coupon_code", orderServiceGoodDetail.getCouponCode());
                orderDetail.put("verify_time", orderServiceGoodDetail.getVerifyTime());
                //获取券码二维码base64字符流
                String couponQrcodestr = CodeUtil.getBase64QRcodeStr(QRCodeParams.initialize(orderServiceGoodDetail.getCouponCode(),
                        400, 400, 0xFF000000, 0xFFFFFFFF, 2, null));
                orderDetail.put("coupon_qrcode", couponQrcodestr);
                orderDetail.put("coupon_status", orderServiceGoodDetail.getCouponStatus());
                orderServiceGoodDetailList.add(orderDetail);
            }
            if (orderServiceGoodDetailList.size() > 0) {
                map.put("detail_list", orderServiceGoodDetailList);
            }


            //可退款数量
            Short total;
            if (orderServiceGood.getUsedNumber() != null) {
                total = (short) (orderServiceGood.getNumber() - orderServiceGood.getUsedNumber());
            } else {
                total = orderServiceGood.getNumber();
            }
            if (total != 0) {
                //可退订单金额= (购买优惠券数量/可使用数量)*订单总金额
                BigDecimal retreatAmount = new BigDecimal(orderServiceGood.getNumber()).divide(new BigDecimal(total))
                        .multiply(new BigDecimal(tradeOffline.getOrderAmount()));
                map.put("retreatAmount", retreatAmount);
            } else {
                map.put("retreatAmount", "0");
            }

            // 查询可核销门店列表
            List<Shop> shops = shopMapper.selectCanVerifyShopListByServiceGoodId(orderServiceGood.getGoodId());
            List<Map<String, Object>> shopList = new ArrayList<Map<String, Object>>();
            for (Shop shop : shops) {
                Map<String, Object> shopMap = new HashMap<String, Object>();
                shopMap.put("shop_id", shop.getId());
                shopMap.put("shop_name", shop.getMerchantName());
                shopMap.put("work_time", shop.getWorkTime());
                shopMap.put("shop_phone", shop.getPhone());
                shopMap.put("shop_address", shop.getAddress());
                shopList.add(shopMap);
            }
            if (shopList.size() > 0) {
                map.put("shop_list", shopList);
            }

            List<MallGoodComment> mallGoodComments = mallGoodCommentMapper.selectMemberOrderComment(Long.parseLong(memberId), orderServiceGood.getId());
            List<Map<String, Object>> commentList = new ArrayList<Map<String, Object>>();
            for (MallGoodComment mallGoodComment : mallGoodComments) {
                Map<String, Object> goodCommentMap = new HashMap<String, Object>();
                goodCommentMap.put("comment_id", mallGoodComment.getId());
                goodCommentMap.put("member_icon", mallGoodComment.getMemberIcon());
                goodCommentMap.put("member_name", mallGoodComment.getMemberName());
                goodCommentMap.put("score", mallGoodComment.getCommentLevel());
                goodCommentMap.put("comment_date", DateUtil.fomatDate(mallGoodComment.getGmtCreate(), DateUtil.sdfTime));
                goodCommentMap.put("comment_content", mallGoodComment.getContent());
                goodCommentMap.put("pic_urls", mallGoodComment.getPicUrls());
                goodCommentMap.put("shop_id", mallGoodComment.getShopId());
                goodCommentMap.put("shop_name", mallGoodComment.getShopName());
                commentList.add(goodCommentMap);
            }
            if (commentList.size() > 0) {
                map.put("comment_list", commentList);
            }

        }

        return map;

    }


    @Override
    public int updateOrderStatus(String memberId, String orderId, String masterUrl) throws Exception {
        int result = 0;
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }
        if (Tools.isEmpty(orderId)) {
            throw new ApplicationException(Rescode.FAIL, "orderId不能为空！");
        }

        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(orderId, (byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        if (tradeOffline != null) {
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Cancel.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            //将锁定的积分和优惠券进行解锁
            int j = bonusVerifyLogMapper.updateStatusByOrderId(tradeOffline.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());

            int z = memberMapper.updateMemberBonusUnlock(tradeOffline.getPayerId(), tradeOffline.getBonusAmount());

            //如果使用了优惠券，就更改优惠券使用状态，分为会员优惠券解锁和非会员优惠券解锁
            List<CouponUser> couponUsers = couponUserMapper.selectByOrderId(tradeOffline.getId());
            if(couponUsers != null && couponUsers.size()>0){
                couponUserMapper.updateUnlockCouponOnMemberByOrderId(tradeOffline.getId());
                couponUserMapper.updateUnlockCouponOnNoMemberByOrderId(tradeOffline.getId());
            }

        }

        result = orderServiceGoodMapper.updateCancelOrder(BizEnum.ServiceOrderStatus.OrderCancel.getType(), orderId);

        try {
            templateMailSendService.sendOrderTemplate(tradeOffline.getOrderId(), BizEnum.WebTemplateType.template12.getType(), tradeOffline.getPayerId(), tradeOffline.getGroupId(), masterUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public Map<String, Object> getNameByPhone(String phone, String groupId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Member member = memberMapper.queryNameByPhone(phone, Long.parseLong(groupId));
        if (member != null) {
            map.put("memberId", member.getId());
            map.put("name", member.getName());
        }
        return map;
    }

    //修改登入密码
    @Override
    public Boolean updatePassword(String memberId, String newPassword, String oldPassword) throws ApplicationException {
        //根据会员id查询userId
        Member member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        Userbase userbase = userBaseMapper.selectByPrimaryKey(member.getUserId());
        if (userbase == null) {
            throw new ApplicationException(Rescode.FAIL, "用户信息不存在");
        }
        String passwd = new SimpleHash("SHA-1", userbase.getUsername(), oldPassword).toString();
        if (passwd.equals(userbase.getPassword())) {
            userbase.setId(member.getUserId());
            userbase.setPassword(new SimpleHash("SHA-1", userbase.getUsername(), newPassword).toString());
            userbase.setGmtModified(new Date());
            userBaseMapper.updateByPrimaryKeySelective(userbase);
        } else {
            throw new ApplicationException(Rescode.FAIL, " 原始密码输入不对,不能去修改");
        }
        return true;
    }

    @Override
    public Boolean updateTradePassword(String memberId, String newPassword, String oldPasssword) throws ApplicationException {
        Member member = memberMapper.queryGroup(Long.parseLong(memberId));
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "用户信息不存在");
        }

        if (member.getTradePassword().equals("888888")) {
            member.setId(Long.parseLong(memberId));
            member.setTradePassword(AES.AESEncode(Const.AceKey, newPassword));
            memberMapper.updateByPrimaryKeySelective(member);
        } else if (AES.AESEncode(Const.AceKey, oldPasssword).equals(member.getTradePassword())) {
            member.setId(Long.parseLong(memberId));
            member.setTradePassword(AES.AESEncode(Const.AceKey, newPassword));
            member.setGmtCreate(new Date());
            member.setGmtModified(new Date());
            memberMapper.updateByPrimaryKeySelective(member);
        } else {
            throw new ApplicationException(Rescode.FAIL, " 原始支付密码输入不对,不能去修改");
        }
        String userId = member.getVirtualCard();
        String sysTraceNum = DateUtil.getDays() + Tools.getRandomNum(4);//交易流水号12位
        String groupId = member.getPayGroupCode();
        String orgTranDateTime = DateUtil.getSdfTimes();
        String orgOrderNum = orgTranDateTime + Tools.getRandomNum(4);
        PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(userId, oldPasssword, newPassword, groupId, sysTraceNum, orgTranDateTime, orgOrderNum);
        PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
        if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
//	    	throw new ApplicationException(Rescode.FAIL, " 支付密码修改失败");
            throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
        }
        return true;
    }

    //重置支付密码
    @Override
    public Boolean updatetradePassword(String memberId, String password) throws ApplicationException {
        System.out.println("-------------------------------重置支付密码----------------------" + password);
        Member member = memberMapper.queryGroup(Long.parseLong(memberId));
        if (member != null) {
            MemberInDTO memberInDTO = new MemberInDTO();
            memberInDTO.setId(Long.parseLong(memberId));
            String userId = member.getVirtualCard();
            String sysTraceNum = DateUtil.getDays() + Tools.getRandomNum(4);//交易流水号12位
            String groupId = member.getPayGroupCode();
            String orgTranDateTime = DateUtil.getSdfTimes();
            String orgOrderNum = orgTranDateTime + Tools.getRandomNum(4);
            String payPwd = member.getTradePassword();
            String tradePassword = AES.AESEncode(Const.AceKey, password);
            System.out.println("-------------------------------秘钥----------------------" + Const.AceKey);
            System.out.println("-------------------------------加密支付密码----------------------" + tradePassword);
            System.out.println("-------------------------------解密支付密码----------------------" + AES.AESDncode(Const.AceKey, tradePassword));
            System.out.println("-------------------------------数据库解密支付密码----------------------" + AES.AESDncode(Const.AceKey, payPwd));
            member.setTradePassword(tradePassword);
            memberMapper.updateByPrimaryKeySelective(member);
            PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(userId, AES.AESDncode(Const.AceKey, payPwd),
                    password, groupId, sysTraceNum, orgTranDateTime, orgOrderNum);
            PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                System.out.println("-------------------------------支付密码重置----------------------");
                FindbackPayPwd payUpdateRestPwd = FindbackPayPwd.initialize(member.getVirtualCard(),
                        password,
                        member.getPayGroupCode(),
                        sysTraceNum,
                        orgTranDateTime,
                        "000000",
                        "000000");
                PayResult payResultRest = IPayAPI.findbackAccountPayPwd(payUpdateRestPwd);
                if (!PayResult.SUCCESS.equals(payResultRest.getRespCode())) {
                    throw new ApplicationException(Rescode.FAIL, " 支付密码重置失败");
                }
            }
        } else {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        return true;
    }

    @Override
    public Boolean updateTradePasswordOne(String memberId, String newPassword) throws ApplicationException {
        Member member = memberMapper.queryGroup(Long.parseLong(memberId));
        String oldPwd = AES.AESDncode(Const.AceKey, member.getTradePassword());
        member.setId(Long.parseLong(memberId));
        member.setTradePassword(AES.AESEncode(Const.AceKey, newPassword));
        member.setGmtCreate(new Date());
        member.setGmtModified(new Date());
        memberMapper.updateByPrimaryKeySelective(member);
        MemberInDTO memberInDTO = new MemberInDTO();
        memberInDTO.setId(Long.parseLong(memberId));
        String userId = member.getVirtualCard();
        String sysTraceNum = DateUtil.getDays() + Tools.getRandomNum(4);//交易流水号12位
        String groupId = member.getPayGroupCode();
        String orgTranDateTime = DateUtil.getSdfTimes();
        String orgOrderNum = orgTranDateTime + Tools.getRandomNum(4);
        PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(userId, oldPwd, newPassword, groupId, sysTraceNum, orgTranDateTime, orgOrderNum);
        PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
        if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
            throw new ApplicationException(Rescode.FAIL, " 支付密码修改失败");
        }
        return true;
    }

    //重置登入密码
    @Override
    public Boolean passwordUpdate(String memberId, String password) throws ApplicationException {

        Member member = memberMapper.findById(Long.parseLong(memberId));
        if (member != null) {
            Userbase userbase = userBaseMapper.selectByPrimaryKey(member.getUserId());
            if (userbase != null) {
                userbase.setPassword(new SimpleHash("SHA-1", userbase.getUsername(), password).toString());
                userbase.setGmtModified(new Date());
                userBaseMapper.updateByPrimaryKeySelective(userbase);
            } else {
                throw new ApplicationException(Rescode.FAIL, "用户信息不存在");
            }
        } else {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        return true;
    }

    //重置支付密码
    @Override
    public Boolean tradePasswordUpdate(String memberId, String password) throws ApplicationException {
        Member member = memberMapper.queryGroup(Long.parseLong(memberId));
        String newPwd = AES.AESEncode(Const.AceKey, password);
        if (member != null) {
            MemberInDTO memberInDTO = new MemberInDTO();
            memberInDTO.setId(Long.parseLong(memberId));
            String userId = member.getVirtualCard();
            String sysTraceNum = DateUtil.getDays() + Tools.getRandomNum(4);//交易流水号12位
            String groupId = member.getPayGroupCode();
            String payPwd = member.getTradePassword();
            String orgTranDateTime = DateUtil.getSdfTimes();
            String orgOrderNum = orgTranDateTime + Tools.getRandomNum(4);
            member.setTradePassword(newPwd);
            memberMapper.updateByPrimaryKeySelective(member);
            PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(userId, payPwd, newPwd, groupId, sysTraceNum, orgTranDateTime, orgOrderNum);
            PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, " 支付密码修改失败");
            }
        } else {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        return true;
    }

    @Override
    public Map<String, Object> queryMemberId(String shopId, String phone) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        ShopGroupRelation shop = shopGroupRelationMapper.queryGroupByshopId(Long.parseLong(shopId));
        Member member =memberMapper.queryMemberByPhone(phone,shop.getGroupId());
        map.put("memberId",member.getId());
        return map;
    }


    @Override
    public Map<String, Object> myInvitewelfareList(String memberId, String date, Integer pageNo, Integer pageSize) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (Tools.isEmpty(date)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (pageNo == null) {
            throw new ApplicationException(Rescode.FAIL, "pageNo 不能为空！");
        }
        if (pageSize == null) {
            throw new ApplicationException(Rescode.FAIL, "pageSize 不能为空！");
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("memberId", Long.parseLong(memberId));
        param.put("date", date);
        param.put("limit", pageSize);
        param.put("start", pageSize * (pageNo - 1));

        List<Map> walfares = activityRoutineRegisterMapper.selectInviteWalfareByMemberId(param);
        List<Map<String, Object>> walfareList = new ArrayList<Map<String, Object>>();
        for (Map walfare : walfares) {
            Map<String, Object> walfareDetail = new HashMap<String, Object>();
            walfareDetail.put("id", walfare.get("id").toString());
            walfareDetail.put("send_type", walfare.get("send_type").toString());
            walfareDetail.put("gmt_create", DateUtil.fomatDate(walfare.get("gmt_create").toString(), DateUtil.sdfTime));
            if (Integer.parseInt(walfare.get("send_type").toString()) == 4) {//是ji分
                walfareDetail.put("send_name", walfare.get("send_name").toString() + "积分");
                if (Integer.parseInt(walfare.get("send_name").toString()) == Integer.parseInt(walfare.get("first_integral").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("first_people_num").toString() + "人贈送");
                }
                if (Integer.parseInt(walfare.get("send_name").toString()) == Integer.parseInt(walfare.get("second_integral").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("second_people_num").toString() + "人贈送");
                }
                if (Integer.parseInt(walfare.get("send_name").toString()) == Integer.parseInt(walfare.get("third_integral").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("third_people_num").toString() + "人贈送");
                }
            }
            if (Integer.parseInt(walfare.get("send_type").toString()) == 3) {//是優惠券
                walfareDetail.put("send_name", walfare.get("send_name").toString());
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("first_coupon_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("first_people_num").toString());
                }
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("second_coupon_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("second_people_num").toString());
                }
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("third_coupon_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("third_people_num").toString());
                }
            }
            if (Integer.parseInt(walfare.get("send_type").toString()) == 2) {//是紅包
                walfareDetail.put("send_name", walfare.get("send_name").toString());
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("first_redpackage_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("first_people_num").toString() + "人贈送");
                }
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("second_redpackage_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("second_people_num").toString() + "人贈送");
                }
                if (Integer.parseInt(walfare.get("id").toString()) == Integer.parseInt(walfare.get("third_redpackage_id").toString())) {
                    walfareDetail.put("remark", "月邀請" + walfare.get("third_people_num").toString() + "人贈送");
                }
            }


            walfareList.add(walfareDetail);
        }
        if (walfareList.size() > 0) {
            map.put("walfare_list", walfareList);
        }
        return map;
    }

    @Override
    public Map<String, Object> shareInviteQuery(String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }
        MemberInDTO memberInDTO = new MemberInDTO();
        memberInDTO.setId(Long.parseLong(memberId));
        MemberOutDTO member = memberService.queryAmount(memberInDTO);
//		 map.put("opened_status", "1");
        if (member != null) {
            map.put("curBal", member.getCurBal());
            map.put("curBalB", member.getCurBalB());
            map.put("lockBalB", member.getLockBal());
            map.put("lockBal", member.getLockBalB());
        } else {
            map.put("curBal", 0);
            map.put("curBalB", 0);
            map.put("lockBalB", 0);
            map.put("lockBal", 0);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        date = calendar.getTime();
        System.out.println(dateFormat.format(date));
        String date1 = dateFormat.format(date);
        date1 = date1.substring(0, date1.length() - 2);
        String newDate = date1.substring(0, 4) + "年" + date1.substring(4, date1.length()) + '月';

        map.put("lastTime", newDate);
        //本月预估收益 =  本月发展会员 + 本月推荐会员发展返利
//        StatisMember statisMember = statisMemberMapper.shareInviteQuery(Long.parseLong(memberId), new Date());
        Profit profit=profitMapper.memberThisMonthProfit(Long.parseLong(memberId), new Date());
        if(profit !=null){
            map.put("this_profit", profit.getDevelopeProfit());
        }else{
            map.put("this_profit", 0);
        }

        //累计收益(分润 ) 本月推荐会员发展返利
        StatisMember statisMember2 = statisMemberMapper.shareSumProfit(Long.parseLong(memberId));
        if(statisMember2 !=null){
            map.put("this_profit", profit.getDevelopeProfit()+statisMember2.getThisRecommendProfit());
        }else{
            map.put("this_profit", 0);
        }


        //上月推荐人数
//        StatisMemberMonth statisMemberMonth = statisMemberMonthMapper.queryLastMonthData(Long.parseLong(memberId), date1);
//        if (statisMemberMonth != null) {
////            map.put("last_recommend_num", statisMemberMonth.getInviteNumber());//上月推荐人数
//            map.put("last_recommend_num", statisMemberMonth.getInviteNumber() + statisMemberMonth.getRecommendUserCount());//上月推荐人数
//        } else {
//            map.put("last_recommend_num", 0);//上月推荐人数
//        }

        //累计推荐人数 = 发展会员人数  + 推荐会员发展人数 分开显示
        StatisMemberDay statismMemberDay = statisMemberDayMapper.queryMemberInviteCount(Long.parseLong(memberId));
        Member member1=memberMapper.queryAddMemberNumber(Long.parseLong(memberId));
        if(member1 !=null){
            map.put("sum_recommend_num",member1.getAddUserCount());
        }else{
            map.put("sum_recommend_num",0);
        }
        if(statismMemberDay !=null){
            map.put("last_recommend_num",statismMemberDay.getRecommendUserCount());
        }else{
            map.put("last_recommend_num",0);
        }

//        map.put("sum_dev_num",statismMemberDay.getRecommendUserCount());
//        map.put("sum_recommend_num", statismMemberDay.getInviteNumber() + statismMemberDay.getRecommendUserCount());//累计推荐人数


        //上月收益
        ProfitMemberMonth profitMemberMonth = profitMemberMonthMapper.queryLastProfit(Long.parseLong(memberId), date1);
        if (profitMemberMonth != null) {

            map.put("last_profit", profitMemberMonth.getRecommendProfit() + profitMemberMonth.getDevelopeProfit());//上月收益
        } else {
            map.put("last_profit", 0);//上月收益
        }
        //本月预估收益
        /*if (statisMember != null) {
            Calendar c = Calendar.getInstance();
            int today = c.get(c.DAY_OF_MONTH);
            if (today == 1) {
                map.put("this_profit", 0);
            } else {

                map.put("this_profit", statisMember.getThisProfit());
            }
        } else {
            map.put("this_profit", 0);

        }*/
        if (statisMember2 != null) {
            map.put("sum_profit", statisMember2.getSumProfit());//累计收益(分润)
//			map.put("sum_recommend_num",statisMember2.getSumRecommendNum());//累计推荐人数
        } else {
            map.put("sum_profit", 0);
//			map.put("sum_recommend_num",0);
        }



        return map;
    }


    @Override
    public Map<String, Object> updateloginWallet(String memberId, String phone, String loginPassword, String payPassword,
                                                 String certName, String certNum, String rootHomeUrl, String birthday, String sex) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();

        Member member = memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
        Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
        Userbase userbase = userBaseMapper.selectByPrimaryKey(member.getUserId());
        if (member == null || group == null) {
            throw new ApplicationException(Rescode.FAIL, "用户信息不存在");
        }
        if (Tools.notEmpty(member.getVirtualCard())) {
            throw new ApplicationException(Rescode.FAIL, "不能重复注册");
        }
        Member memberPost = memberMapper.selectByPrimaryPhone(member.getGroupId(), phone, BizEnum.MemberDevelopeMode.PosConsume.getType());
        //如该手机号码pos机 已开户，账户合并处理
        if (memberPost != null && Tools.notEmpty(memberPost.getVirtualCard())) {
            String oldPwd = null;
            if (Tools.notEmpty(memberPost.getTradePassword())) {
                oldPwd = AES.AESDncode(Const.AceKey, memberPost.getTradePassword());
            }
            //关注会员标识
            Long userId_at = member.getUserId();
            Long memberId_at = member.getId();
            Userbase userbasePost = userBaseMapper.selectByPrimaryKey(memberPost.getUserId());
            if (userbasePost != null) {
                userbasePost.setUsername(phone);
                userbasePost.setPassword(new SimpleHash("SHA-1", phone, loginPassword).toString());
                //更新原账户信息
                userBaseMapper.updateByPrimaryKey(userbasePost);
            }
            String payPassword_ = AES.AESEncode(Const.AceKey, payPassword);
            memberPost.setOpenid(member.getOpenid());
            memberPost.setWeixinName(member.getWeixinName());
            memberPost.setWxsubStaus(BizEnum.WebChatConcernStatus.Concerned.getType());
            memberPost.setPicture(member.getPicture());
            memberPost.setTradePassword(payPassword_);//交易密码
            memberPost.setUpdateTime(new Date());
            memberPost.setConcernTime(member.getConcernTime());
            memberPost.setPerfectTime(null);
            memberPost.setUnconcernMemberNum(null);
            memberPost.setSex(Integer.valueOf(sex));
            if (Tools.notEmpty(certName) && Tools.notEmpty(certNum)) {
                memberPost.setIdNo(certNum);
                memberPost.setName(certName);
            }
            //更新当前pos机信息
            if (Tools.notEmpty(birthday)) {
                memberPost.setBirthday(DateUtil.fomatDate(birthday));
            }
            //删除关注会员信息
            userBaseMapper.deleteByPrimaryKey(userId_at);
            memberMapper.deleteByPrimaryKey(memberId_at);
            
            //openId做了唯一索引 需要先删除原来的进行 再更新记录
            memberMapper.updateByPrimaryKeySelective(memberPost);
            
            String userId = memberPost.getVirtualCard();
            String groupId = group.getPayGroupCode();
            if (Tools.notEmpty(certName) && Tools.notEmpty(certNum)) {//不为空 实名认证
                PayUpdateData ud = PayUpdateData.initialize(
                        groupId,
                        userId,
                        certName,
                        member.getPhone(),
                        certNum,
                        DateUtil.fomatDate(new Date(), DateUtil.sdfTimes),
                        member.getUserId() + "@163.com",
                        null,
                        null, "1");
                PayResult payResultCert = IPayAPI.updateAccountData(ud);
                if (!PayResult.SUCCESS.equals(payResultCert.getRespCode())) {
                    throw new ApplicationException(Rescode.FAIL, payResultCert.getMsgTxt());
                }
            }
            String sysTraceNum = DateUtil.getDays() + Tools.getRandomNum(4);//交易流水号12位
            String orgTranDateTime = DateUtil.getSdfTimes();
            String orgOrderNum = orgTranDateTime + Tools.getRandomNum(4);
            //传给支付平台传明文 2.0存可解密的密文
            PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(userId, oldPwd, payPassword, groupId, sysTraceNum, orgTranDateTime, orgOrderNum);
            PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payResult.getRespCode() + "#" + payResult.getMsgTxt());
            }
            map.put("memberId", memberPost.getId());
            map.put("message", "处理成功");
        } else {
            //普通注册
            Member memberPhone = memberMapper.selectByPrimaryPhone(member.getGroupId(), phone, null);
            if (memberPhone != null) {
                throw new ApplicationException(Rescode.FAIL, "该手机号码已经在该商户开户");
            }
            //支付平台开户
            String GroupId = group.getPayGroupCode();
            String UserId = GroupId + DateUtil.getDays() + Tools.getRandomNum(5);
            String CustomerName = member.getWeixinName();
            String CertNo = "000000000000000000";//长度必须是18位
            String PayPwd = AES.AESEncode(Const.AceKey, payPassword);
            String PwdAnswer = "000000";//安全问题
            String PwdQuest = "000000";//安全答案
            String Email = member.getUserId() + "@163.com";
            String MobilePhone = phone;
            String Level = null;
            String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
            userbase.setUsername(phone);
            userbase.setPassword(new SimpleHash("SHA-1", phone, loginPassword).toString());
            userBaseMapper.updateByPrimaryKey(userbase);
            member.setVirtualCard(UserId);//虚拟卡号 对应支付平台userId
            member.setTradePassword(PayPwd);//交易密码
            member.setWalletStatus(1);//钱包状态(0:未开;1:开通)
            member.setPhone(phone);
            member.setUpdateTime(new Date());
            member.setSex(Integer.valueOf(sex));

            List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(group.getId());
            
            if (Tools.notEmpty(birthday)) {
                member.setBirthday(DateUtil.fomatDate(birthday));
            }


            if (memberGradeList.size()>1) {
                member.setGradeId(memberGradeList.get(1).getId());//会员等级
            }
            String verify = null;
            if (Tools.notEmpty(certName) && Tools.notEmpty(certNum)) {
                member.setApproveStatus(1);
                member.setIdNo(certNum);
                member.setName(certName);
                verify = "1";//为1需要认证
                CustomerName = certName;
                CertNo = certNum;
            } else {
                member.setApproveStatus(0);
                
                if(Tools.isEmpty(certName)){
                	 CustomerName = member.getCardNo();//"无姓名";
                	 member.setName(CustomerName);
                	 if(Tools.isEmpty(certNum)) {
                         CertNo="000000000000000000";
                     } else {
                         CertNo = certNum;
                     }
                     member.setIdNo(CertNo);
                }else{
                	member.setName(certName);
                	CustomerName = certName;
                }
                
                
            }
            try {
                memberMapper.updateByPrimaryKeySelective(member);
            } catch (Exception e) {
                throw new ApplicationException(Rescode.FAIL, "注册会员异常");
            }
            PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId,
                    CustomerName, CertNo,
                    payPassword, PwdAnswer,
                    PwdQuest, Email,
                    MobilePhone,
                    Level, OrgTranDateTime, verify);
            PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
            if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                throw new ApplicationException(Rescode.FAIL, payResult.getRespCode() + "#" + payResult.getMsgTxt());
            }

            //升级去送红包 或优惠券 或积分
            memberService.sendBonusOrRedOrCoupon(member.getId(),member.getGradeId(),group.getId());


            map.put("memberId", member.getId());
            map.put("message", "处理成功");
        }
        return map;
    }


    public Map<String, Object> orderRefund(String memberId, String orderId) throws Exception {

        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
        }
        if (Tools.isEmpty(orderId)) {
            throw new ApplicationException(Rescode.FAIL, "orderId 不能为空！");
        }
//		Map<String, Object> map = new HashMap<String, Object>();

        StringBuffer sb = new StringBuffer();
        //掉支付平台退款给接口
        //Member member = memberMapper.queryPayData(Long.parseLong(memberId),Long.parseLong(orderId));
        Member member = memberMapper.selectByPrimaryKey(Long.parseLong(memberId));
        Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
        TradeOffline tradeOld = tradeOfflineMapper.selectByPrimaryKey(Long.parseLong(orderId));
        String sysTraceNum = StringUtil.getRandNumberStr(12);//交易流水号12位
        String OrgOrderNum = UtilFun.createOrderNum();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = DateUtil.fomatDate(new Date(), DateUtil.sdfTimes);
        UnPayConsumption unPayConsumption = UnPayConsumption.initialize(member.getVirtualCard(), null, group.getPayGroupCode(),
                tradeOld.getOrderAmount().toString(), tradeOld.getPayOrderid(), OrgOrderNum, date, AES.AESDncode(Const.AceKey, member.getTradePassword()), sysTraceNum, "156");
        PayResult payResult = IPayAPI.unPayConsumption(unPayConsumption);
        if (!payResult.getRespCode().equals("0000")) {
            sb.delete(0, sb.length());
            throw new ApplicationException(Rescode.FAIL, sb.append("调用支付平台微信接口失败。(memberId:")
                    .append(memberId).append(")").toString());
        }

        //更新线上交易表
        TradeOffline recordUpdate = new TradeOffline();
        recordUpdate.setId(Long.parseLong(orderId));
        recordUpdate.setTransactionStatus((byte) BizEnum.TransactionStatus.Refund.getType());
        recordUpdate.setGmtModified(new Date());
        tradeOfflineMapper.updateByPrimaryKeySelective(recordUpdate);
        //插入退款记录

        TradeOffline record = new TradeOffline();
        record.setGroupId(member.getGroupId());
        record.setOrderId(tradeOld.getOrderId());
        record.setPayerId(Long.parseLong(tradeOld.getReceiverId()));
        record.setPayerName(tradeOld.getReceiverName());
        record.setPayerType(tradeOld.getReceiverType());
        record.setReceiverId(String.valueOf(tradeOld.getPayerId()));
        record.setReceiverName(tradeOld.getPayerName());
        record.setReceiverType(tradeOld.getPayerType());

        record.setOrderAmount(tradeOld.getOrderAmount() * -1);
        record.setRealAmount(tradeOld.getRealAmount() * -1);
        record.setTransactionType((byte) BizEnum.TransactionType.Refund.getType());
        record.setSubType(tradeOld.getSubType());
        record.setPayType(tradeOld.getPayType());
        record.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());
        record.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        record.setIsWallet(Boolean.TRUE);
        record.setGmtCreate(new Date());
        record.setGmtModified(new Date());
//        record.setRelatedActivityId(tradeOld.getRelatedActivityId());
        record.setOldOrderId(Long.parseLong(orderId));
        record.setPayOrderid(payResult.getOrderId());
        tradeOfflineMapper.insertSelective(record);

        return null;
    }


    @Override
    public Map<String, Object> updateMembercrcode(String memberId) throws Exception {
        // 先根据会员id当前二维码信息是否存在 存在直接使用  不存在 再请求微信临时二维码接口
        String qrcodePicurl = null;
        // expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
        Integer expireSeconds = 2592000;
        Member member = memberMapper.selectByPrimaryKey(Long.valueOf(memberId));
        if (member == null) {
            throw new ApplicationException("会员信息不存在");
        }
//		Group group=groupMapper.selectByPrimaryKey(member.getGroupId());
        GroupWxconfig groupWxconfig = groupWxconfigMapper.queryGroupWxConfigName(member.getGroupId());
        if (groupWxconfig == null) {
            throw new ApplicationException("会员信息不存在");
        }
        Crcode crcode = crcodeMapper.selectUserIdCode(member.getUserId());
        if (crcode != null) {
            //直接查询该二维码信息
            if (crcode.getGmtEnd().after(new Date())) {
                qrcodePicurl = crcode.getQrcodePicurl();
            } else {
                wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(member.getGroupId()));
                WxMpQrCodeTicket ticket = this.wxService.getQrcodeService().qrCodeCreateTmpTicket(Integer.parseInt(memberId), expireSeconds);
                String weixinurl = this.wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket(), true);
                File file = this.wxService.getQrcodeService().qrCodePicture(ticket);
                FileUploadContorller fileUploadContorller = new FileUploadContorller();
                String fileUrl = fileUploadContorller.upload(file, "/file/ebosService/crcode/shop/");
                Date date = new Date();
                crcode.setGmtCreate(date);
                crcode.setGmtModified(date);
                crcode.setQrcodeLinkUrl(weixinurl);//二维码链接URL
                crcode.setQrcodeName("会员专属二维码");
                crcode.setQrcodePicurl(fileUrl);//二维码图片URL
                crcode.setScanTimes(0);
                crcode.setUserId(member.getUserId());
                crcode.setStatus(1);
                crcode.setUserId(member.getUserId());
                crcode.setType(BizEnum.MemberDevelopeFrom.UserDevelope.getType());
                crcode.setSceneid(new Integer(member.getId().intValue()));//场景值 直接取会员id
                //结束时间 为当前时间+场景值有效时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.SECOND, expireSeconds);
                crcode.setGmtEnd(calendar.getTime());
                crcodeMapper.updateByPrimaryKey(crcode);
                qrcodePicurl = fileUrl;
            }
        } else {
            //二维码不存在 需要重新生成 并保存该二维码
            wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(member.getGroupId()));
            WxMpQrCodeTicket ticket = this.wxService.getQrcodeService().qrCodeCreateTmpTicket(Integer.parseInt(memberId), expireSeconds);
            String weixinurl = this.wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket(), true);
            File file = this.wxService.getQrcodeService().qrCodePicture(ticket);
            FileUploadContorller fileUploadContorller = new FileUploadContorller();
            String fileUrl = fileUploadContorller.upload(file, "/file/ebosService/crcode/shop/");
            Crcode memberCrcode = new Crcode();
            Date date = new Date();
            memberCrcode.setGmtCreate(date);
            memberCrcode.setGmtModified(date);
            memberCrcode.setQrcodeLinkUrl(weixinurl);//二维码链接URL
            memberCrcode.setQrcodeName("会员邀请专属二维码");
            memberCrcode.setQrcodePicurl(fileUrl);//二维码图片URL
            memberCrcode.setScanTimes(0);
            memberCrcode.setUserId(member.getUserId());
            memberCrcode.setStatus(1);
            memberCrcode.setUserId(member.getUserId());
            memberCrcode.setType(BizEnum.MemberDevelopeFrom.UserDevelope.getType());//BizEnum.CrcodeType.member.getType()
            memberCrcode.setSceneid(new Integer(member.getId().intValue()));//场景值 直接取会员id
            //结束时间 为当前时间+场景值有效时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.SECOND, expireSeconds);
            memberCrcode.setGmtEnd(calendar.getTime());
            crcodeMapper.insert(memberCrcode);
            qrcodePicurl = fileUrl;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("qrcodePicurl", qrcodePicurl);
        map.put("picture", member.getPicture());
        map.put("name", member.getName());
//		map.put("groupName", group.getMerchantName());
        map.put("groupName", groupWxconfig.getWxAppname());
        return map;
    }


    @Override
    public Map<String, Object> queryPaycrcode(String memberId, String temporary_, String logoPath, String NotifyUrl) throws ApplicationException {
        Map<String, Object> map = new HashMap<String, Object>();
        Member member = memberMapper.queryGroup(Long.valueOf(memberId));
        Integer expireSeconds = 15;//付款码有效时间为60秒
        String qrcodePicurl = null;
        String qrcode = null;
        if (member != null) {
            Crcode crcode = crcodeMapper.selectUserIdPayCode(member.getUserId());
            //	String temporary =member.getCardNo()+".png";
            if (crcode != null) {
                //直接查询该二维码信息
                if (crcode.getGmtEnd().after(new Date())) {
                    qrcodePicurl = crcode.getQrcodePicurl();
                    qrcode = crcode.getQrcode();
                } else {
                    PayReqQRCode payReqQRCode = PayReqQRCode.initialize(member.getPayGroupCode(), member.getVirtualCard(), NotifyUrl);
                    PayResult payResult = IPayAPI.userReqQRCodeService(payReqQRCode);
                    if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                        throw new ApplicationException(payResult.getRespCode() + "#" + payResult.getMsgTxt());
                    }
                    try {
                        qrcode = Rsa.finishDentryKeenData(Global.KEY_PATH, payResult.getMsgTxt());
                        FileOutputStream fos = null;
                        File file = new File(temporary_);
                        fos = new FileOutputStream(file);
                        CodeUtil.encode(fos, QRCodeParams.initialize(qrcode, 400, 400, 0xFF000000, 0xFFFFFFFF, 2, logoPath, member.getCardNo()));
                        FileUploadContorller fileUploadContorller = new FileUploadContorller();
                        String fileUrl = fileUploadContorller.upload(file, "/file/ebosService/crcode/paycrcode/");
                        Date date = new Date();
                        crcode.setGmtCreate(date);
                        crcode.setGmtModified(date);
                        crcode.setQrcodeLinkUrl(null);
                        crcode.setQrcodeName("会员付款专属二维码");
                        crcode.setQrcodePicurl(fileUrl);//二维码图片URL
                        crcode.setScanTimes(0);
                        crcode.setUserId(member.getUserId());
                        crcode.setStatus(1);
                        crcode.setUserId(member.getUserId());
                        crcode.setType(BizEnum.ScancrcodeType.walletCode.getType());
                        crcode.setSceneid(null);
                        crcode.setQrcode(qrcode);
                        //结束时间 为当前时间+场景值有效时间
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        calendar.add(Calendar.SECOND, expireSeconds);
                        crcode.setGmtEnd(calendar.getTime());
                        crcodeMapper.updateByPrimaryKey(crcode);
                        qrcodePicurl = fileUrl;
                    } catch (Exception e) {
                        throw new ApplicationException(Rescode.FAIL, "文件处理异常");
                    }
                }
            } else {
                PayReqQRCode payReqQRCode = PayReqQRCode.initialize(member.getPayGroupCode(), member.getVirtualCard(), NotifyUrl);
                PayResult payResult = IPayAPI.userReqQRCodeService(payReqQRCode);
                if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
                    throw new ApplicationException(payResult.getRespCode() + "#" + payResult.getMsgTxt());
                }
                qrcode = Rsa.finishDentryKeenData(Global.KEY_PATH, payResult.getMsgTxt());
                FileOutputStream fos = null;
                File file = new File(temporary_);
                try {
                    fos = new FileOutputStream(file);
                    CodeUtil.encode(fos, QRCodeParams.initialize(qrcode, 400, 400, 0xFF000000, 0xFFFFFFFF, 2, logoPath, member.getCardNo()));
                    FileUploadContorller fileUploadContorller = new FileUploadContorller();
                    String fileUrl = fileUploadContorller.upload(file, "/file/ebosService/crcode/paycrcode/");
                    Crcode memberCrcode = new Crcode();
                    memberCrcode.setGmtCreate(new Date());
                    memberCrcode.setGmtModified(new Date());
                    memberCrcode.setQrcodeLinkUrl(null);
                    memberCrcode.setQrcodeName("会员付款专属二维码");
                    memberCrcode.setQrcodePicurl(fileUrl);//二维码图片URL
                    memberCrcode.setScanTimes(0);
                    memberCrcode.setUserId(member.getUserId());
                    memberCrcode.setStatus(1);
                    memberCrcode.setUserId(member.getUserId());
                    memberCrcode.setType(BizEnum.ScancrcodeType.walletCode.getType());
                    memberCrcode.setSceneid(null);
                    memberCrcode.setQrcode(qrcode);
                    //结束时间 为当前时间+场景值有效时间
                    Calendar calendar = Calendar.getInstance();
                    Date date = new Date();
                    calendar.setTime(date);
                    calendar.add(Calendar.SECOND, expireSeconds);
                    memberCrcode.setGmtEnd(calendar.getTime());
                    crcodeMapper.insert(memberCrcode);
                    qrcodePicurl = fileUrl;
                } catch (Exception e) {
                    throw new ApplicationException(Rescode.FAIL, "文件处理异常");
                }
            }
            TradeOffline tradeMax = tradeOfflineMapper.Maxmarked(member.getId());
            if (tradeMax == null) {
                map.put("marked", 1);
            } else {
                map.put("marked", tradeMax.getMarked() + 1);
            }
            map.put("qrcodePicurl", qrcodePicurl);
            map.put("qrcode", qrcode);
            return map;
        } else {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }

    }

    @Override
    public Map<String, Object> queryPaycrcode(String memberId, String NotifyUrl) throws ApplicationException {
        Member member = memberMapper.queryGroup(Long.valueOf(memberId));
        Map<String, Object> map = new HashMap<String, Object>();
        if (member == null) {
            throw new ApplicationException(Rescode.FAIL, "会员信息不存在");
        }
        PayReqQRCode payReqQRCode = PayReqQRCode.initialize(member.getPayGroupCode(), member.getVirtualCard(), NotifyUrl);
        PayResult payResult = IPayAPI.userReqQRCodeService(payReqQRCode);
        if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
            throw new ApplicationException(payResult.getRespCode() + "#" + payResult.getMsgTxt());
        }
        TradeOffline tradeMax = tradeOfflineMapper.Maxmarked(Long.valueOf(memberId));
        if (tradeMax == null) {
            map.put("marked", 1);
        } else {
            map.put("marked", tradeMax.getMarked() + 1);
        }
        String qrcode = Rsa.finishDentryKeenData(Global.KEY_PATH, payResult.getMsgTxt());
        map.put("qrcode", qrcode + "&" + member.getCardNo());
        return map;
    }


    @Override
    public Map<String, Object> queryPayCallback(PayCrcodeCallback payCrcodeCallback) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(payCrcodeCallback.getOrgOrderNum());
        TradeOffline tradeMax = tradeOfflineMapper.Maxmarked(tradeOffline.getPayerId());
        if (tradeMax == null) {
            tradeOffline.setMarked(1L);
        } else {
            tradeOffline.setMarked(tradeMax.getMarked() + 1);
        }
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
        return null;
    }


    @Override
    public Map<String, Object> queryPayPolling(String memberId, String marked) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectByMaxmarked(Long.valueOf(memberId), Long.valueOf(marked));
        if (tradeOffline != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("qrcodeCreateDate", tradeOffline.getGmtCreate());
            map.put("qrcodeStatus", "支付成功");
            map.put("qrcodeTranAmt", tradeOffline.getOrderAmount());
            map.put("qrcodeOrgOrderNum", tradeOffline.getOrderId());
            return map;
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Object> queryWxInfo(String memberId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }
        MemberWxInfoDTO memberWxInfo = memberMapper.queryWxInfo(Long.parseLong(memberId));
        MemberWxInfoDTO memberWxUpdateInfo = memberMapper.queryWxUpdateGradeInfo(Long.parseLong(memberId));

        if (memberWxInfo != null) {
            map.put("avator", memberWxInfo.getMemberPicture());
            map.put("member_name", memberWxInfo.getMemberName());
            map.put("card_num", memberWxInfo.getCardNo());
            map.put("member_level", memberWxInfo.getMemberGradeName());
            map.put("current_consume", memberWxInfo.getConsumeAmount());
            map.put("bonus_amount", memberWxInfo.getBonusAmount());
            if (memberWxUpdateInfo == null) {
                map.put("nextLevel_minConsume", 0);
                map.put("member_nextlevel", "");
            } else {
                map.put("nextLevel_minConsume", memberWxUpdateInfo.getNextLevelMinConsume());
                map.put("member_nextlevel", memberWxUpdateInfo.getMemberNextGradeName());
            }
        }
        return map;

    }


    @Override
    public Map<String, Object> queryRedpackageUser(String memberId, String redpackageId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (Tools.isEmpty(memberId)) {
            throw new ApplicationException(Rescode.FAIL, "memberId不能为空！");
        }
        if (Tools.isEmpty(redpackageId)) {
            throw new ApplicationException(Rescode.FAIL, "redpackageId不能为空！");
        }
        RedpackageUser redpackageUser = redpackageUserMapper.queryGetRedpackageUser(Long.parseLong(memberId), Long.parseLong(redpackageId));
        if (redpackageUser != null) {
            map.put("amount", redpackageUser.getFaceValue());
            map.put("date", new Date());
            if (StringUtil.isEmpty(redpackageUser.getFaceValue()) || redpackageUser.getFaceValue() == null) {
                map.put("amount", StringUtil.getRandNumberStr(redpackageUser.getMinValue(), redpackageUser.getMaxValue()));
            }
            redpackageUser.setId(redpackageUser.getId());
            redpackageUser.setGetStatus(ActivityEnum.RedpackageGetStatus.Gotten.getType());
            redpackageUserMapper.updateByPrimaryKeySelective(redpackageUser);

        }
        return map;

    }

    @Override
    public Boolean updateTransOrgOrderNum(String qrCode, String orgOrderNum, String rootHomeUrl) {
        TradeOffline tradeOffline = tradeOfflineMapper.selectPayId(orgOrderNum);
        if (tradeOffline != null) {
            tradeOffline.setCrcodeStr(qrCode);
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            TradeOffline tradeMax = tradeOfflineMapper.Maxmarked(tradeOffline.getPayerId());
            if (tradeMax == null) {
                tradeOffline.setMarked(1L);
            } else {
                Long marked = tradeMax.getMarked() + 1;
                tradeOffline.setMarked(marked);
            }
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            try {
                templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template11.getType(), tradeOffline.getPayerId(),
                        tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), rootHomeUrl);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return true;
    }


    @Override
    public Map<String, Object> queryCodeSuccessDetails(String orderNum) throws ApplicationException {
        TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderIdStatus(orderNum, (byte) BizEnum.TransactionStatus.Success.getType());
        if (tradeOffline == null) {
            throw new ApplicationException(Rescode.FAIL, "未查询到交易记录！");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        TradeOffline tradeOfflineRelated = tradeOfflineMapper.selectRelatedTradeOfflineId(tradeOffline.getId(), (byte) BizEnum.TransactionStatus.Success.getType());
        if (tradeOfflineRelated != null) {
            map.put("backAmt", Double.valueOf(tradeOfflineRelated.getOrderAmount()) / 100);
        } else {
            map.put("backAmt", "0");
        }
        map.put("consume_merchant", tradeOffline.getReceiverName());
        map.put("trade_order", tradeOffline.getOrderId());
        map.put("tradeTime", DateUtil.fomatDate(tradeOffline.getGmtCreate(), DateUtil.sdfTimeC));
        map.put("agency_number", tradeOffline.getPayOrderid());
        map.put("trade_money", Double.valueOf(tradeOffline.getOrderAmount()) / 100);// 订单金额
        map.put("deduct_intergral", Double.valueOf(tradeOffline.getBonusValue()) / 100);//积分抵扣
        map.put("deduct_coupon", Double.valueOf(tradeOffline.getDiscountAmount()) / 100);// 优惠券抵扣
        map.put("real_amount", Double.valueOf(tradeOffline.getRealAmount()) / 100);
        map.put("pay_type", BizEnum.PaymentType.fromType(tradeOffline.getPayType()).getName());
        map.put("order_fee", Double.valueOf(tradeOffline.getFee()) / 100);
        map.put("trade_status", "支付成功");
        return map;
    }


}

